﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace crm_library.Javascript
{
	public static class Alert
	{
		public enum AlertMessageType
		{
			/// <summary>
			/// Notes that the message should show to an end user.
			/// </summary>
			Message,

			/// <summary>
			/// Notes that the message should show in a local debug environment only, and a generic error message should show to an end user.
			/// </summary>
			Error,

		}

		public static void ShowSucceedOrFail(string itemSucceeded, bool success)
		{
			if (success)
			{
				Show(itemSucceeded + " succeeded.", AlertMessageType.Message);
			}
			else
			{
				Show(itemSucceeded + " failed.", AlertMessageType.Message);
			}
		}

		public static void ShowSuccess(string itemSucceeded, string redirect = null, bool newWindow = false)
		{
			Show(itemSucceeded + " succeeded", AlertMessageType.Message, redirect, newWindow);
		}

		public static void ShowFailure(string itemSucceeded, string redirect = null, bool newWindow = false)
		{
			Show(itemSucceeded + " failed", AlertMessageType.Message, redirect, newWindow);
		}

		public static void Show(IEnumerable<string> messages, AlertMessageType errorType, string redirect = null, bool newWindow = false)
		{
			Show(string.Join("\n", messages), errorType, redirect, newWindow);
		}

		public static void Show(string message, AlertMessageType errorType, string redirect = null, bool newWindow = false)
		{


			var customErrors = HttpContext.Current.IsCustomErrorEnabled;
			if (errorType == AlertMessageType.Message) customErrors = false;

			var script = new StringBuilder();

			script.Append("<script type=\"text/javascript\">alert('");
			script.Append(customErrors
							  ? "Process threw an exception but custom errors is disabled. Please report the exact steps taken which caused the problem."
							  : message.Replace("'", "\\'").Replace('\n', ' ').Replace('\r', ' ')
							  );
			script.Append("');");


			if (!string.IsNullOrEmpty(redirect))
			{
				if (newWindow)
				{
					script.Append("window.open('" + redirect + "')");
				}
				else
				{
					script.Append("location = \"" + redirect + "\";");
				}
			}

			script.Append("</script>");

			var page = HttpContext.Current.CurrentHandler as System.Web.UI.Page;
			if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert"))
			{
				page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script.ToString());
			}
		}
	}
}

